<template>
  <div>
    <n-card :bordered="false">
      <!-- 页面标题 -->
      <h2>{{ isEdit ? '编辑配置' : '添加配置' }}</h2>

      <!-- 配置表单 -->
      <n-form ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="120px"
        :style="{ maxWidth: '300px' }">
        <n-form-item label="AGV 编号" path="agv_index">
          <n-input-number v-model:value="model.agv_index" />
        </n-form-item>
        <n-form-item label="AGV 类型" path="agv_type">
          <n-input v-model:value="model.agv_type" />
        </n-form-item>
        <n-form-item label="IP 地址" path="remote_host">
          <n-input v-model:value="model.remote_host" />
        </n-form-item>
        <n-form-item label="远程端口" path="remote_port">
          <n-input-number v-model:value="model.remote_port" />
        </n-form-item>
        <n-form-item label="本地端口" path="local_port">
          <n-input-number v-model:value="model.local_port" />
        </n-form-item>
        <n-form-item label="响应超时" path="timeout">
          <n-input-number v-model:value="model.timeout" />
        </n-form-item>
        <n-form-item label="发送间隔" path="timesend">
          <n-input-number v-model:value="model.timesend" />
        </n-form-item>
        <n-form-item label="启用状态" path="isenable">
          <n-select v-model:value="model.isenable" :options="isenableOptions" />
        </n-form-item>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <n-button @click="handleCancel">取消</n-button>
          <n-button type="primary" :loading="loading" @click="handleValidateButtonClick">{{ isEdit ? '更新' : '提交'
          }}</n-button>
        </div>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import { NCard, NForm, NFormItem, NInput, NInputNumber, useMessage, NButton, NSelect, NPopconfirm } from "naive-ui";
import { ref, onMounted } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { API_URLS } from '../../utils/apiConfig';

const router = useRouter();
const route = useRoute();
const message = useMessage();

// 状态管理
const loading = ref(false);
const isEdit = ref(false);

// 声明formRef
const formRef = ref(null);
const AGV_car_Index = ref(null);

// 表单数据模型
const model = ref({
  id: null,
  agv_index: 1, // 数字（必填）
  agv_type: "3MC_15", // 字符串（必填）
  remote_host: "127.0.0.1", // 字符串（IP，必填）
  remote_port: 0, // 数字（端口，必填）
  local_port: 0, // 数字（端口，必填）
  timeout: 3000, // 数字（必填）
  timesend: 1000, // 数字（必填）
  isenable: 0, // 数字（0/1，必填）
});

// 表单验证规则
const rules = {
  agv_index: { type: "number", required: true, trigger: ["blur", "change"], message: "请输入AGV编号" },
  agv_type: { type: "string", required: true, trigger: ["blur", "change"], message: "请输入AGV类型" },
  remote_host: {
    type: "string",
    required: true,
    trigger: "blur",
    message: "请输入IP地址",
    validator(rule, value) {
      const ipReg = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
      if (ipReg.test(value)) return true;
      return new Error("请输入有效的IP地址（如127.0.0.1）");
    },
  },
  remote_port: { type: "number", required: true, trigger: ["blur", "change"], message: "请输入本地端口", min: 1, max: 65535 },
  local_port: { type: "number", required: true, trigger: ["blur", "change"], message: "请输入远程端口", min: 1, max: 65535 },
  timeout: { type: "number", required: true, trigger: ["blur", "change"], message: "请输入响应超时时间", min: 1 },
  timesend: { type: "number", required: true, trigger: ["blur", "change"], message: "请输入发送间隔", min: 1 },
  isenable: { type: "number", required: true, trigger: ["blur", "change"], message: "请选择启用状态", min: 0, max: 1 },
};

// 站点类型选项
const isenableOptions = [
  { label: "启用", value: 1 },
  { label: "禁用", value: 0 },
];

// 检查是否为编辑模式;
onMounted(() => {
  //从路由参数中获取站点ID;
  const id = route.params.id;
  if (id) {
    isEdit.value = true;
    AGV_car_Index.value = id;
    fetch_AGV_Detail(); // 加载配置详情
  }
});

// 获取配置详情（编辑模式）
const fetch_AGV_Detail = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${API_URLS.agv.detail}/${AGV_car_Index.value}`, {
      params: {},
    });
    if (response.data.code === 200) {
      model.value = response.data.data;
    } else {
      message.error(`获取配置详情失败: ${response.data.msg}`);
      router.push("/AGV/AGV_car_list");
    }
  } catch (error) {
    message.error(`获取配置详情失败: ${error.message}`);
    router.push("/AGV/AGV_car_list");
  } finally {
    loading.value = false;
  }
};

// 验证逻辑
function handleValidateButtonClick() {
  formRef.value?.validate((errors) => {
    if (!errors) {
      // message.success("验证成功");
      add_data();
    } else {
      console.log("数据验证失败：", errors);
      message.error("数据验证失败，请检查输入");
    }
  });
}

// 添加设备按钮 确认
function handlePositiveClick() {
  handleValidateButtonClick();
}

// 添加设备按钮 取消
function handleNegativeClick() {
  message.info("已取消");
}

// 添加数据
const add_data = async () => {
  if (!formRef.value) return;

  try {
    // 验证表单数据
    await formRef.value.validate();
    loading.value = true;

    let response;
    if (isEdit.value) {
      // 编辑模式 - PUT请求
      response = await axios.put(API_URLS.agv.update, { ...model.value, id: AGV_car_Index.value },
        { params: {}, }
      );
    } else {
      // 添加模式 - POST请求
      response = await axios.post(API_URLS.agv.create, model.value, { params: {}, });
    }

    if (response.data.code === 200) {
      model.value.agv_index = model.value.agv_index + 1;
      model.value.remote_port = model.value.remote_port + 1;
      message.success(`设备${isEdit.value ? "更新" : "创建"}成功:${response.data.msg}`);
    } else {
      message.error(`设备${isEdit.value ? "更新" : "创建"}失败: ${response.data.msg}`);
    }
  } catch (error) {
    // 错误处理逻辑：获取并打印状态码和详细信息
    if (error.response) {
      // 后端有响应（如400/401/402等状态码）
      const statusCode = error.response.status; // HTTP状态码（如402）
      const detail = error.response.data.detail || "未知错误信息"; // 提取detail字段

      // 后端返回错误码 及错误信息
      message.error(`数据新增错误: ${detail} (状态码: ${statusCode})`);
    } else if (error.request) {
      message.error("网络错误: ", error.message);
    } else {
      message.error("其他错误: " + error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.push("/AGV/AGV_car_list");
};
</script>

<style scoped>
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>
